package com.rlyy.rsj.job.statistic;

import com.rlyy.rsj.common.JobConstans;
import com.rlyy.rsj.job.DoUpBilJob;
import com.rlyy.rsj.job.IScheduler;
import com.rlyy.rsj.utils.DistributeLock;
import com.rlyy.rsj.utils.RedisKeyFactory;
import com.rlyy.rsj.utils.RedisUtils;
import common.util.DateTimeFormatterUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;

import static com.rlyy.rsj.utils.DistributeLock.oneMinute;

/**
 * 定时统计生产产品使用情况
 *
 * @author yuanqinglong
 * @since 2021/3/9 18:09
 */
@Component
public class StatisticProductUsage implements IStatisticUsageJob, IScheduler {

    private static final String LOCK_KEY = RedisKeyFactory.wrapJobKey(StatisticProductUsage.class.getName());
    private static final String STATUS_KEY = RedisKeyFactory.wrapJobKey("prod_usage");
    private static final String HEALTH_KEY = RedisKeyFactory.wrapJobKey("prod_health");

    @Override
    @Scheduled(cron = "0 30 0 * * ?")
    public void scheduler() {
        try {
            boolean lock = DistributeLock.lock(LOCK_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), oneMinute);
            if (lock) {
                LocalDate yesterday = LocalDate.now().minusDays(1);
                this.performStatistics(yesterday, JobConstans.PRODUCE_ENVIRONMENT);
                logger.info("{}-统计生产环境-产品使用情况定时任务：执行时间:{}",LOCAL_INFO, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()));
                RedisUtils.set(STATUS_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), -1);
                DistributeLock.unlock(LOCK_KEY);
            } else {
                logger.warn("{}-未执行生产环境-产品使用情况定时任务",LOCAL_INFO);
            }
        } catch (Exception e) {
            logger.error("{}-定时统计生产产品使用情况启动失败 !",LOCAL_INFO, e);
            throw new RuntimeException("定时统计生产产品使用情况 启动失败 !", e);
        }
        //统计存活状态
        RedisUtils.hset(HEALTH_KEY, LOCAL_INFO, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()));
    }


    /**
     * 统计产品使用量SQL语句
     *
     * @param statisticsDate 统计日期
     * @param orgId          统计机构id
     * @return SQL
     */
    @Override
    public String statisticalSqlStatement(LocalDate statisticsDate, String orgId) {
//        String orgCondition = StringUtils.isBlank(orgId) ? " AND org_id IS NOT NULL " : " AND org_id = '" + orgId + "'";
        String orgCondition = StringUtils.isBlank(orgId) ? " AND aut_org_id IS NOT NULL " : " AND aut_org_id = '" + orgId + "'";
        String dateZone = " AND (log_storagetime < '" + statisticsDate.plusDays(1) + "' AND log_storagetime >= '" + statisticsDate + "')";
//        return " SELECT log_prod_uid ,prod_name ,COUNT(*) AS stat_useamount, " +
//                " log_orgp_id,org_id,org_sname,log_storagetime::DATE as log_storagetime " +
//                " FROM sys.oper_log LEFT JOIN sys.sys_prod ON prod_uid = log_prod_uid " +
//                " LEFT JOIN sys.sys_orgp orgp ON orgp.orgp_id =log_orgp_id LEFT JOIN sys.sys_org ON org_id = orgp.orgp_org_id " +
//                " WHERE  log_iscost ='" + JobConstans.IS_COST + "' AND " + dateZone + orgCondition +
//                " GROUP BY log_orgp_id,log_prod_uid,prod_name,org_id,org_sname,log_storagetime::DATE; ";


        return " SELECT " +
//                "   org_id AS stat_org_id, " +
                "   aut_org_id AS stat_org_id, " +
                "   log_orgp_id AS stat_orgp_id, " +
                "   log_prod_uid AS stat_prod_uid, " +
                "   max(prod_name) AS stat_prod_name, " +
                "   log_storagetime ::date AS stat_date, " +
                "   count(*) AS stat_req_num, " +
                "   sum(case when query_fback_no = '2' then 1 else 0 end ) AS stat_findout_num, " +
                "   sum(case when query_fback_no = '1' then 1 else 0 end ) AS stat_null_num, " +
                "   sum(case when query_fback_no = '0' then 1 else 0 end ) AS stat_fail_num, " +
                "   sum(case when log_iscost = '1' then 1 else 0 end ) AS stat_charge_num, " +
                "   sum(case when log_dscost = '1' then 1 else 0 end ) AS stat_up_useamount " +
                " FROM sys.oper_log " +
                " LEFT JOIN sys.sys_prod ON prod_uid = log_prod_uid " +
                " LEFT JOIN sys.sys_orgp orgp ON orgp.orgp_id =log_orgp_id " +
//                " LEFT JOIN sys.sys_org ON org_id = orgp.orgp_org_id " +
                " LEFT JOIN sys.sys_authon ON log_user_id = aut_keyid " +
                " WHERE log_orgp_id IS NOT NULL " + dateZone + orgCondition +
//                " GROUP BY org_id,log_orgp_id,log_prod_uid,log_storagetime::date; ";
                " GROUP BY aut_org_id,log_orgp_id,log_prod_uid,log_storagetime::date; ";

    }


}
